#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/shm.h>

#include "alg.8-0-shmdata.h"
 
int main(int argc, char *argv[])
{
    void *shmptr = NULL;
    struct shared_struct *shared = NULL;
    int shmid;
    key_t key;

    char buffer[BUFSIZ + 1]; /* 8192bytes, saved from stdin */
    
    sscanf(argv[1], "%x", &key);

    printf("shmwrite: IPC key = %x\n", key);

    shmid = shmget((key_t)key, sizeof(int) * 2 + TEXT_NUM*sizeof(struct shared_struct), 0666|PERM);
    if (shmid == -1) {
        ERR_EXIT("shmwite: shmget()");
    }

    shmptr = shmat(shmid, 0, 0);
    if(shmptr == (void *)-1) {
        ERR_EXIT("shmwrite: shmat()");
    }
    printf("shmwrite: shmid = %d\n", shmid);
    printf("shmwrite: shared memory attached at %p\n", shmptr);
    printf("shmwrite precess ready ...\n");
    printf("hello world\n");

    int *rear_ptr = (int *) shmptr;
    int *front_ptr = rear_ptr+1;
    shmptr += 8;

    printf("%p %p %p\n",rear_ptr, front_ptr, shmptr);

    shared = (struct shared_struct *)shmptr;
    
    struct shared_struct * start_ptr = shared;
    
    while (1) {
        
        int flag = 0;
        
        while (*front_ptr != *rear_ptr) {
            printf("%d %d", *front_ptr, *rear_ptr);
            sleep(2); /* message not ready, waiting ... */
        }
        while((*rear_ptr + 1) % TEXT_NUM != *front_ptr)
        {

            start_ptr = shared +  *rear_ptr;
            printf("Enter some text for name: ");
            scanf("%s",buffer);
            strncpy(start_ptr->student_name, buffer, TEXT_SIZE);
            
            printf("start_ptr buffer: %s\n",start_ptr->student_name);

            printf("Enter some text for id: ");
            scanf("%s",buffer);
            strncpy(start_ptr->student_id, buffer, TEXT_SIZE);
                        
            (*rear_ptr)  = (* rear_ptr + 1) % TEXT_NUM;

            if(strncmp(buffer, "end", 3) == 0) {                
                flag = 1;               
                *front_ptr = (*rear_ptr + 1) % TEXT_NUM ;
                break;
            }

            printf("rear: %d %d\n", *rear_ptr, *front_ptr);         
        }
        if (flag){
            break;
        }   
    }
       /* detach the shared memory */
    if(shmdt(shmptr-8) == -1) {
        ERR_EXIT("shmwrite: shmdt()");
    }

//    sleep(1);
    exit(EXIT_SUCCESS);
}
